-- UIGroupBuyInfo
-- Create by huanghr
-- 团购信息界面

require "game/ui/form/group_buy/UIGroupBonusDesc"

-- UIGroupBuyInfo继承自Layer
UIGroupBuyInfo = class("UIGroupBuyInfo", function()
    return cc.Layer:create();
end);

function UIGroupBuyInfo.create(goodsId)
    return UIGroupBuyInfo.new(goodsId);
end

-- 构造函数
function UIGroupBuyInfo:ctor(goodsId)
    -- 初始化
    self:setName("UIGroupBuyInfo");
    local node = cc.CSLoader:createNode("layout/market/GroupBuyInfo.csb");
    self:addChild(node);
    self.node = node;

    self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);

    local CT = node:getChildByName("CT");
    local scrollview = CT:getChildByName("scrollview");
    self.CT = CT;
    self.scrollView = scrollview;

    self.goodsId = goodsId;
    self.list = ME.user:getAllPetIds();
    local info = MarketM.getGoodsInfo(goodsId);
    self.heroId = info.bonus[1][2];

    -- 隐藏template中的背景
    self:hideTemplateBg();

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 初始化格子
    self:initGrids();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 适配
function UIGroupBuyInfo:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 初始化格子
function UIGroupBuyInfo:initGrids()
    local node = self.node;

    local scrollview = self.scrollView;

    -- 图标间距(横向)
    local wGap = 5;

    -- 图标间距(纵向)
    local hGap = 5;

    -- 图标宽度
    local iconWidth = 100;

    -- 图片高度
    local iconHeight = 150;

    local topHGap  = 1;
    local leftWGap = 3;

    -- 获取团购的团购可领取的总次数
    local maxTimes = GroupPurchaseM.query(self.goodsId, "max_times");

    self.scrollView:removeAllChildren();

    -- item的名字
    local itemName = "bonus";

    -- 计算行数
    local totalNum = maxTimes;

    -- 左边距
    local leftMargin = 1;

    -- 行间距
    local gap = 0;
    local widgetHeight = 61;

    local startHeight = 10;

    --计算总高度
    local totalHeight = math.max(totalNum * (widgetHeight + gap), scrollview:getInnerContainerSize().height);
    startHeight = totalHeight;

    if totalHeight < scrollview:getInnerContainerSize().height then
        startHeight = scrollview:getInnerContainerSize().height;
    end

    scrollview:setInnerContainerSize(cc.size(scrollview:getInnerContainerSize().width, totalHeight));

    local itemNode = cc.CSLoader:createNode("layout/market/BonusItem.csb");
    local widget = replaceNodeWithWidget(itemNode);

    for n = 1, totalNum do
        local child = widget:clone();
        child:setName(itemName .. n);

        local x = leftMargin;
        local y = startHeight - n * (widgetHeight + gap) - 10;
        if n == 1 then
            local line2 = findChildByName(child, "line2");
            line2:setVisible(true);
        end
        child:setPositionX(x);
        child:setPositionY(y);

        self:registerItemTouchEvent(child, n);

        scrollview:addChild(child);
    end
end

-- 显示英雄选择界面
function UIGroupBuyInfo:redraw()
    -- 显示标题
    -- 显示冈布奥的名称
    local petName = PetM.query(self.heroId, "name");
    local titleLabel = findChildByName(self.CT, "template/title");
    titleLabel:setString(petName);
    TextStyleM.setTitleStyle(titleLabel);

    -- 现有的团购进度
    local hasBuy = GroupPurchaseM.fetchProgress(self.goodsId);
    local progress = 0;
    if hasBuy ~= nil then
        progress = hasBuy.progress;
    end

    local str2 = string.format(getLocStr("cur_have_bought"), progress);

    local subHeadLabel = findChildByName(self.CT, "template/subhead");
    subHeadLabel:setString(str2);
    TextStyleM.setSubheadStyle(subHeadLabel);

    -- 显示冈布奥信息
    local petBg1  = findChildByName(self.CT, "pet_bg1");
    local petBg2  = findChildByName(self.CT, "pet_bg2");
    local petIcon = findChildByName(self.CT, "pet_bg3/icon");

    -- 英雄头像
    local fileName = PetM.getDefaultIcon(self.heroId);
    local iconPath = getHeroIconPath(fileName);

    petBg1:loadTexture(iconPath);
    petBg1:setOpacity(80);
    petBg2:loadTexture(iconPath);
    petBg2:setOpacity(80);

    petIcon:loadTexture(iconPath);

    -- 显示星级
    local starNode = findChildByName(self.CT, "pet_bg3/star");
    self:redrawHeroStar(starNode, self.heroId);

    -- 显示购买描述
    local tipLabel = findChildByName(self.CT, "tip_label");
    local str = getLocStr("group_buy_tip");
    TextStyleM.setTextStyle(tipLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);

    local petName = PetM.query(self.heroId, "name");

    applyString(tipLabel, string.format(str, petName));


    -- 获取团购的团购可领取的总次数
    local maxTimes = GroupPurchaseM.query(self.goodsId, "max_times");

    local totalGridCount = maxTimes;

    -- 显示信息
    for i = 1, totalGridCount do
        local grid = self.scrollView:getChildByName("bonus" .. i);
        if grid then
            --  初始化格子信息
            self:initGridInfo(grid, i);
        end
    end

    -- 如果未购买该冈布奥领取按钮置灰,不领取时按钮置灰
    local gainBtn = findChildByName(self.node, "BT/gain_btn");
    if table.indexOf(self.list, self.heroId) == - 1 or GroupPurchaseM.calcBonusAmountById(self.goodsId) < 1 then
        gainBtn:setBright(false);
        gainBtn:setTouchEnabled(false);
    end
    TextStyleM.setTextStyle(gainBtn, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    gainBtn:setTitleText(getLocStr("take_bonus"));

    -- 检查冒泡
    local hintNode = findChildByName(gainBtn, "hint");
    local canTakeAmount = GroupPurchaseM.calcBonusAmountById(self.goodsId);
    checkBlueBubbleStatus(hintNode, canTakeAmount);
end

-- 重绘英雄星级
function UIGroupBuyInfo:redrawHeroStar(starNode, classId)
    local hero = PetM.getMyPet(classId);
    if not hero then
        return;
    end

    -- 获取英雄阶位
    local starNum = hero:getRank();
    local maxStarNum = PetM.getMaxUpgradeRank();
    if maxStarNum < 1 then
        maxStarNum = 1;
    end

    if maxStarNum < starNum then
        maxStarNum = starNum;
    end

    -- 生成星星层，直接挂到结点上
    -- TODO
    local lightStarPath = "images/ui/symbol/star_little.png";
    local layer = createStarLayer(starNum, lightStarPath, "center", -0.7);
    if not layer then
        return;
    end

    starNode:removeAllChildren();
    starNode:addChild(layer);
end

--  初始化格子信息
function UIGroupBuyInfo:initGridInfo(grid, i)
    -- 奖品图片
    local icon = findChildByName(grid, "item_icon");
    local itemNameLabel = findChildByName(grid, "item_label");

    -- 领奖标示
    local tip = findChildByName(grid, "take_label");

    local light = findChildByName(grid, "light");
    light:setVisible(false);

    -- 计算当前奖励物品
    local bonusInfo = GroupPurchaseM.calcBonus(self.goodsId, i);
    local iconPath = "";
    local itemName = "";
    local str1     = "";
    if bonusInfo[1] == 1 then
        local fileIcon = ItemM.query(bonusInfo[2], "icon");
        iconPath = getItemIconPath(fileIcon);
        itemName = ItemM.query(bonusInfo[2], "name");
        str1     = itemName .. "×" .. tostring(bonusInfo[3]);
    else
        local fileIcon = FieldsM.query(bonusInfo[2], "icon");
        iconPath = getLargeAttribIconPath(fileIcon);
        itemName = FieldsM.query(bonusInfo[2], "name")
        str1     = itemName .. "+" .. tostring(bonusInfo[3]);
    end

    icon:loadTexture(iconPath);

    itemNameLabel:setString(str1);

    -- 计算已领取过奖励的的level
    local level =  GroupPurchaseM.hasTookLevel(self.goodsId);

    if i <= level then
        TextStyleM.setTextStyle(tip, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_GRAY);
        TextStyleM.setTextStyle(itemNameLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_GRAY);
        tip:setString(getLocStr("has_received"));
    else

        -- 如果当前奖励可领取数字蓝，不可领取数字红色
        -- 计算某个等级所需要的团购人数
        local peopleNum = GroupPurchaseM.getRequire(self.goodsId, i);

        -- 购买过该冈布奥的人数
        local hasBuy = GroupPurchaseM.fetchProgress(self.goodsId);
        local progress = 0;
        if hasBuy ~= nil then
            progress = hasBuy.progress;
        end

        local maxLevel = GroupPurchaseM.maxBonusLevel(self.goodsId);
        if peopleNum <= progress and table.indexOf(self.list, self.heroId) ~= - 1 then
            TextStyleM.setTextStyle(tip, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_GREEN);
            TextStyleM.setTextStyle(itemNameLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_GREEN);
            tip:setString(getLocStr("can_be_taken"));

            light:setVisible(true);
            local rotateForever = cc.RepeatForever:create(cc.RotateBy:create(30, 360));
            light:runAction(rotateForever);

            playBubbleAnima2(icon, false, 0.6);
        else
            local str = string.format("%d/%d", progress, peopleNum);
            TextStyleM.setTextStyle(tip, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_DARK_BROWN);
            TextStyleM.setTextStyle(itemNameLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_DARK_BROWN);
            tip:setString(str);
        end
    end
end

-- 注册商品点击事件
function UIGroupBuyInfo:registerItemTouchEvent(node, index)
    -- 点击处理
    local bonusList = GroupPurchaseM.calcBonus(self.goodsId, index);
    local bg = node:getChildByName("bg");

    -- 物品奖励的时候才需要显示奖励内容
    if bonusList[1] == 1 then
        bg:addTouchEventListener(function(sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                AudioM.playFx("workshop_material");
                -- 显示道具详细信息
                local uiItemDesc = UIGroupBonusDesc.create(bonusList, self.goodsId, index);
                UIMgr:getCurrentScene():addForm(uiItemDesc);
            end
        end);
    end
end

-- 注册事件处理回调函数
function UIGroupBuyInfo:registerEventCallback()
    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            cclog("UIGroupBuyInfo 界面析构清理");
            EventMgr.removeAll("UIGroupBuyInfo");

            -- 刷新团购界面
            local uiForm = UIMgr.getCurrentScene():getFormByName("UIGroupPurChase");
            if uiForm then
                uiForm:redraw();
            end

        elseif eventType == "enter" then

        end
    end);
end

-- 注册点击事件
function UIGroupBuyInfo:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UIGroupBuyInfo");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 注册领奖按钮
    local gainBtn = findChildByName(self.node, "BT/gain_btn");
    local function onGainClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 查看能不能领取
            local hasTookLevel =  GroupPurchaseM.hasTookLevel(self.goodsId);
            local maxTimes = GroupPurchaseM.query(self.goodsId, "max_times");

            -- 领取次数超过
            if hasTookLevel >= maxTimes then
                alert(string.format(getLocStr("cant_gain_bonus2")));
                AudioM.playFx("button_receive_failed");
                return;
            end

            --
            if not GroupPurchaseM.canTakeBonus(self.goodsId, hasTookLevel + 1) then
                alert(getLocStr("cant_gain_bonus1"));
                AudioM.playFx("button_receive_failed");
               return;
            end

            -- 领取奖励
            if GroupPurchaseM.takeBonus(self.goodsId, hasTookLevel + 1) then
                local bonus = GroupPurchaseM.calcBonus(self.goodsId, hasTookLevel + 1);
                local bonusList = {};
                table.insert(bonusList, bonus);

                if bonusList ~= nil and #bonusList > 0 then
                    showBonusNotifyForm(getLocStr("group_buy_bonus"), bonusList);
                end
                self:redraw();

                -- 重绘团购页面
                local uiForm = UIMgr.getCurrentScene():getFormByName("UIMarketMain");
                if uiForm then
                    -- 隐藏底部信息
                    uiForm:showGroupBuy(false);
                end
            end
        end
    end
    gainBtn:addTouchEventListener(onGainClick);
    TextStyleM.setTextStyle(gainBtn, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    gainBtn:setTitleText(getLocStr("take_bonus"));
end

-- 隐藏template上部的bg
function UIGroupBuyInfo:hideTemplateBg()
    local template = findChildByName(self.node, "CT/template");
    local bgType   = findChildByName(template, "bg_type");
    local bgType2  = findChildByName(template, "bg_type2");
    bgType:setVisible(false);
    bgType2:setVisible(false);
end